extends Sprite2D


# Called when the node enters the scene tree for the first time.

@export var grid:TileMapLayer
@export var speed:float
@export var target_player: Node2D
var random_generator = RandomNumberGenerator.new()
var timeCount:float = 0.0
var timeLimit:float = 3.0

var target_path: Array[Vector2i]
var last_dir: Vector2

func _ready() -> void:
	random_generator.randomize()
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	# if Input.is_action_just_pressed("up_move"):
	# 	$AnimationPlayer.play("1052_up")
	# if Input.is_action_just_pressed("down_move"):
	# 	$AnimationPlayer.play("1052_down")
	# if Input.is_action_just_pressed("left_move"):
	# 	$AnimationPlayer.play("1052_left")
	# if Input.is_action_just_pressed("right_move"):
	# 	$AnimationPlayer.play("1052_right")
	if global_position.distance_to(target_player.global_position) < 40:
		visible = true
	else: 
		visible = false
	
	timeCount += delta
	#if Input.is_action_just_pressed("click"):
	if timeCount > timeLimit:
		timeCount = 0.0
		timeLimit *= random_generator.randf_range(0.8, 1.2)
		speed *=  random_generator.randf_range(0.8, 1.2)
		var mouse_pos = target_player.global_position #get_global_mouse_position()
		var start_co = grid.local_to_map(global_position)
		var target_co = grid.local_to_map(mouse_pos)
		target_path = grid.astar.get_id_path(start_co, target_co)
		#print(target_path)
		
	if target_path and not target_path.is_empty():
		var target_pos = grid.map_to_local(target_path[0])
		#判定角色方向
		var direction = (target_pos - global_position).normalized()
		if(direction != Vector2.ZERO and direction != last_dir):
			#print("change direction cur"+str(direction)+"last"+str(last_dir))
			if direction.x > 0:
				$AnimationPlayer.play("1052_right")
			elif direction.x < 0:
				$AnimationPlayer.play("1052_left")
			elif direction.y > 0:
				$AnimationPlayer.play("1052_down")
			elif direction.y < 0:
				$AnimationPlayer.play("1052_up")

		last_dir = direction
		global_position = global_position.move_toward(target_pos, 100 * delta* speed)
		
		if global_position == target_pos:
			target_path.remove_at(0)				
	pass



